import { login, logout, getInfo } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
  },

  actions: {
    // ��¼
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((resultDTO) => {
            const token = resultDTO.data;
            setToken(token);
            commit('SET_TOKEN', token);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // ��ȡ�û���Ϣ
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((resultDTO) => {
            const user = resultDTO.data?.user;
            const avatar =
              user.avatar == '' || user.avatar == null
                ? require('@/assets/images/profile.jpg')
                : process.env.VUE_APP_BASE_API + user.avatar;
            if (resultDTO.data?.roles && resultDTO.data?.roles.length > 0) {
              // ��֤���ص�roles�Ƿ���һ���ǿ�����
              commit('SET_ROLES', resultDTO.data?.roles);
              commit('SET_PERMISSIONS', resultDTO.data?.permissions);
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT']);
            }
            commit('SET_NAME', user.userName);
            commit('SET_AVATAR', avatar);
            resolve(resultDTO);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // �˳�ϵͳ
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit('SET_TOKEN', '');
            commit('SET_ROLES', []);
            commit('SET_PERMISSIONS', []);
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // ǰ�� �ǳ�
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '');
        removeToken();
        resolve();
      });
    },
  },
};

export default user;
